//
//  GTFlutterViewController.swift
//  GTFlutter
//
//  Created by Shper on 2023/5/15.
//

import Foundation
import Flutter

open class GTFlutterViewController: FlutterViewController {

    // 导航 EventChannel 通知，控制原生容器 手势侧滑
    var basicMessageChannel: FlutterBasicMessageChannel?
    public var isControllNavigation: Bool = true
    public var shouldDestroyEngine: Bool = false
    public var onInteractivePopChanged: ((Bool) -> Void)?
    public var onViewWillAppear: (() -> Void)?
    
    // 初始化 initRouterName
    public var initRouterName: String = ""
    // Flutter 引擎 ID
    public var engineId: String = ""
    
    public init(initRouterName: String,
                engine: FlutterEngine,
                engineId: String? = nil,
                isControllNavigation: Bool? = true,
                nibName: String? = nil,
                bundle: Bundle? = nil) {
        print("GTFlutter - init \(initRouterName)")
        
        self.initRouterName = initRouterName
        self.engineId = engineId ?? ""
        self.isControllNavigation = isControllNavigation ?? true

        super.init(engine: engine, nibName: nibName, bundle: bundle)
    }
    
    required public init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func viewWillAppear(_ animated: Bool) {
        print("GTFlutter - viewWillAppear \(initRouterName)")
        
        super.viewWillAppear(animated)
        
        if (isControllNavigation) {
            controllNavigation()
        }
        onViewWillAppear?()
    }
    
    // 控制原生导航栏
    private func controllNavigation() {
        print("GTFlutter - controllNavigation")
        
        // 注册 Flutter 路由导航 EventChannel 通知，控制原生容器 手势侧滑
        basicMessageChannel = FlutterBasicMessageChannel(name: "com.gateio.flutter.navigation",
                                                         binaryMessenger: self.binaryMessenger,
                                                         codec: FlutterStringCodec.sharedInstance())
        basicMessageChannel?.setMessageHandler { (message, reply) in
            // 注册侧滑手势改变的监听，当 Flutter 还能 pop 时说明容器内部 page 大于1，将不允许原生容器的侧滑手势
            guard let messageStr = message as? String, !messageStr.isEmpty else {
                return
            }
            guard let dict = self.toDictionary(messageStr) else {
                return
            }
            
            let flutterPageCanPop = dict["flutterPageCanPop"] as? Bool ?? false
            self.onInteractivePopChanged?(flutterPageCanPop)
        }
    }
    
    override public func viewWillDisappear(_ animated: Bool) {
        print("GTFlutter - viewWillDisappear \(initRouterName)")

        super.viewWillDisappear(animated)
        
        // 注销 EventChannel 通知，释放内存
        basicMessageChannel?.setMessageHandler(nil)
        basicMessageChannel = nil
    }
    
    override public func viewDidDisappear(_ animated: Bool) {
        print("GTFlutter - viewDidDisappear \(initRouterName)")

        super.viewDidDisappear(animated)
    }
    
    deinit {
        print("GTFlutter - deinit \(initRouterName)")
        // 清除列表
        GTFlutter.shared.removePageStartedList(routerName: initRouterName)
        if shouldDestroyEngine {
            engine?.destroyContext()
        }
    }
    
    private func toDictionary(_ str: String)-> [String:Any]? {
        guard let data = str.data(using: String.Encoding.utf8) else{
            return nil
        }
        guard let dict = try? JSONSerialization.jsonObject(with: data,
                                                           options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String:Any] else {
            return nil
        }
        return dict
    }

}
